package coms.mianshi.proxy.dynaticproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: item_02
 * @description: 动态代理
 * @author: LL
 * @create: 2021-03-02 13:57
 */

//静态代理对象实现IUserDao接口
public class UserDapProxy {

    private Object target;//维护一个目标对象

    public UserDapProxy(final Object target) {
        this.target = target;
    }

    //目标对象生成代理对象
    public Object getUserDapProxy() {
        return Proxy.newProxyInstance(this.target.getClass().getClassLoader(),
                this.target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
                        System.out.println("开始事务");
                        //执行目标对象方法
                        final Object returnValue = method.invoke(UserDapProxy.this.target, args);
                        System.out.println("结束事务");
                        return null;
                    }
                });
    }

    public static void main(final String[] args) {
        //目标对象
        final IUserDao target = new UserDao();
        System.out.println(target.getClass());//输出目标对象信息
        final IUserDao proxy = (IUserDao) new UserDapProxy(target).getUserDapProxy();
        System.out.println(proxy.getClass());//输出代理对象信息
        proxy.save();//执行代理方法
    }
}
